#!/usr/bin/env python 2.7
# -*- coding: utf-8 -*-
# @Time      :2019/4/10
# @Author    :breeze
# @Email     :wangbaoshan@bbdservice.com
# @File      :IC08_SingleConsLoanAmt
# @Software  :PyCharm


'''eof
name:个人消费贷款笔均金额
code:IC08_SingleConsLoanAmt_2D
tableName:
columnName:
groups:个人征信模块
dependencies:IC_DSJ_2D
type:常用指标
datasourceType:在线指标
description:
eof'''

import json
import sys
import re
import datetime

reload(sys)
sys.setdefaultencoding('utf-8')

null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']


def getTable(data, tableName, occurTimes, iteratorTimes):
    '''
        获取表信息
        :param data:表上层的字典对象
        :param tableName:表的名字
        :param occurTimes:表出现的次数，如果是0代表此表可以不出现，如果是1代表此表必须出现
        :param iteratorTimes:下级字段出现的次数，如果是0代表下级字段可以不出现，如果是1代表下级字段必须出现
        :return:该表全部数据  返回[{}]为异常缺失，返回0为正常缺失，其他返回正常数组
        '''
    try:
        table = data.get(tableName)
        if occurTimes == 0:
            if table is None or (table == "" and iteratorTimes == 0):
                return 0
            elif isinstance(table, list) is False or len(table) == 0 or (table == "" and iteratorTimes == 1):
                return [{}]
            else:
                return table
        if occurTimes == 1:
            if table == "" and iteratorTimes == 0:
                return 0
            if table is None or isinstance(table, list) is False or len(table) == 0 \
                    or (table == "" and iteratorTimes == 1):
                return [{}]
            else:
                return table
    except:
        return [{}]


def floatCheck(str):
    try:
        float(str)
        return True
    except:
        return False


def singleConsLoanAmt():
    data = IC_DSJ_2D.get('data')
    factor = []
    factor2 = []
    # 借贷账户信息 PDA[1.1]
    PDA = getTable(data, 'PDA', 1, 0)
    if PDA == [{}]:
        return u'缺失值'
    elif PDA == 0:
        return 0
    else:
        # 借贷账户信息单元 PD01[0.*]
        PD01 = getTable(PDA[0], 'PD01', 0, 1)
        if PD01 == [{}]:
            return u'缺失值'
        elif PD01 == 0:
            return 0
        else:
            for i in PD01:
                try:
                    # 基本信息段 PD01A[1.1]
                    PD01A = getTable(i, 'PD01A', 1, 1)
                    if PD01A == [{}]:
                        factor.append(None)
                    elif PD01A == 0:
                        factor.append(0)
                        factor2.append(0)
                    else:
                        # 业务种类
                        PD01AD03 = PD01A[0].get("PD01AD03")
                        # 借款金额
                        PD01AJ01 = PD01A[0].get("PD01AJ01")
                        # 账户授信额度
                        PD01AJ02 = PD01A[0].get("PD01AJ02")

                        if PD01AD03 not in null_type_list:
                            if PD01AD03 == "21" or PD01AD03 == "53" or PD01AD03 == "91":
                                factor2.append(1)
                                if floatCheck(PD01AJ01):
                                    factor.append(float(PD01AJ01))
                                if floatCheck(PD01AJ02):
                                    factor.append(float(PD01AJ02))
                            else:
                                factor.append(0)
                                factor2.append(0)
                        else:
                            factor.append(None)
                            factor2.append(None)
                except:
                    factor.append(None)
                    continue

    factor = [x for x in factor if x is not None]
    factor2 = [x for x in factor2 if x is not None]
    if len(factor) == 0 or len(factor2) == 0:
        return u'缺失值'
    else:
        try:
            if sum(factor2) == 0:
                return 0
            return '%.4f' % (sum(factor) / sum(factor2))
        except:
            return u'缺失值'


if __name__ == '__main__':
    file_obj = open(r'../../data/IC/IC08_SingleConsLoanAmt/IC.json', 'r')
    content = file_obj.read()
    IC_DSJ_2D = json.loads(content, strict=False)
    aa = singleConsLoanAmt()
    print aa

result = singleConsLoanAmt()
